package com.kmproject.haifu.mvp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.hfinterface.PopuWindowSearchHistoryInterface;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.app.utils.PopuwindowContralUtils;
import com.kmproject.haifu.di.component.DaggerSecondHandListShowComponent;
import com.kmproject.haifu.mvp.contract.SecondHandListShowContract;
import com.kmproject.haifu.mvp.model.api.Api;
import com.kmproject.haifu.mvp.model.entity.beans.HousePayWayBean;
import com.kmproject.haifu.mvp.model.entity.beans.SecondHandCategoryBean;
import com.kmproject.haifu.mvp.model.entity.beans.SecondHandInfoBean;
import com.kmproject.haifu.mvp.model.entity.resbean.PopuWindowSelectSearchBean;
import com.kmproject.haifu.mvp.model.entity.resbean.SecondHandQueryParmar;
import com.kmproject.haifu.mvp.presenter.SecondHandListShowPresenter;
import com.kmproject.haifu.mvp.ui.adapter.PopuWindowSelectPxAdapter;
import com.kmproject.haifu.mvp.ui.adapter.SecondHandMainShowAdapter;
import com.kmproject.haifu.mvp.ui.holder.AddressSecondHandSelectHolder;
import com.kmproject.haifu.mvp.ui.holder.PxSecondHandSelectHolder;
import com.kmproject.haifu.mvp.ui.holder.SxSecondHandHolder;
import com.kmproject.haifu.mvp.ui.widget.ScaleTransitionPagerTitleView;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.PullToRefreshView;
import com.library.flowlayout.SpaceItemDecoration;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.xw.repo.XEditText;
import com.yyydjk.library.DropDownMenu;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 09/01/2019 10:49
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class SecondHandListShowActivity extends BaseActivity<SecondHandListShowPresenter> implements SecondHandListShowContract.View {

    @BindView(R.id.include_title_search_back)
    ImageView includeTitleSearchBack;
    @BindView(R.id.include_title_search_xedit)
    XEditText includeTitleSearchXedit;
    @BindView(R.id.popuwindow_selectsearchaddress_searchRootlay)
    LinearLayout popuwindowSelectsearchaddressSearchRootlay;
    @BindView(R.id.include_title_search_msg)
    ImageView includeTitleSearchMsg;
    @BindView(R.id.include_title_search_lay)
    LinearLayout includeTitleSearchLay;
    @BindView(R.id.ll_top_search_layout)
    LinearLayout llTopSearchLayout;

    @BindView(R.id.include_title_msg)
    TextView includeTitleMsg;
    @BindView(R.id.include_title_search_search)
    ImageView includeTitleSearchSearch;
    @BindView(R.id.secondhand_show_indicator)
    MagicIndicator secondhandShowIndicator;
    @BindView(R.id.secondhand_serch_result)
    LinearLayout secondhandSerchResult;
    @BindView(R.id.secondhand_title)
    LinearLayout secondhandTitle;
    DropDownMenu dropDownMenu;
    @BindView(R.id.include_title_search_back_img)
    ImageView includeTitleSearchBackImg;
    @BindView(R.id.secondhand_show_view)
    View secondhand_show_view;


    private List<View> popupViews = new ArrayList<>();
    private View addressView, pxView, sxView, contentView;
    private PullToRefreshView HouseRentingShowMain_refreshLayout;
    private RecyclerView HouseRentingShowDuanZuList_RecyclerView;
    private SecondHandMainShowAdapter secondHandMainShowAdapter;
    private List<HousePayWayBean> addressSelectData, kjsxSelectData;
    private HousePayWayBean addressSelectOne;//选择地址，被选中的那一个
    AddressSecondHandSelectHolder addressSecondHandSelectHolder;
    PxSecondHandSelectHolder pxSecondHandSelectHolder;
    SxSecondHandHolder sxSecondHandHolder;
    SecondHandQueryParmar secondHandQueryParmar = new SecondHandQueryParmar();
   boolean isSearchResult=false;//是否是搜索结果页面
    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerSecondHandListShowComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_second_hand_list_show; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initDropDownMenu();
        contolShowUi();
    }

    public void contolShowUi() {
        includeTitleSearchXedit.setEnabled(false);
        if (getIntent().hasExtra("searchContent")) {
            //搜索过来的
            secondhandSerchResult.setVisibility(View.VISIBLE);
            secondhandTitle.setVisibility(View.GONE);
            secondhandShowIndicator.setVisibility(View.GONE);
            secondHandQueryParmar.setKeywords(getIntent().getStringExtra("searchContent"));
            includeTitleSearchXedit.setText(getIntent().getStringExtra("searchContent"));
            secondhand_show_view.setVisibility(View.GONE);
        } else {
            //直接跳转过来的
            secondhand_show_view.setVisibility(View.VISIBLE);
            secondhandShowIndicator.setVisibility(View.VISIBLE);
            secondhandSerchResult.setVisibility(View.GONE);
            secondhandTitle.setVisibility(View.VISIBLE);
            SecondHandCategoryBean secondHandCategoryBean = (SecondHandCategoryBean) getIntent().getSerializableExtra("SecondHandCategoryBean");
            secondHandQueryParmar.setCategoryId(Long.parseLong(secondHandCategoryBean.getCategoryId()));
            includeTitleMsg.setText(secondHandCategoryBean.getName());
            mPresenter.listSecondCategory(secondHandCategoryBean.getCategoryId(), secondHandCategoryBean.getName(), secondHandCategoryBean.getParentId());

            if (secondHandCategoryBean.getName().equals("其他")) {
                secondhandShowIndicator.setVisibility(View.GONE);
            } else {
                flMenuContalShow(secondHandCategoryBean.getChildren());
            }

//          HousePayWayBean housePayWayBean= DataHelper.getDeviceData(this, AppConstant.user_default_select_area);
//        if (housePayWayBean!=null)
//        {
//            dropDownMenu.setTabText(housePayWayBean.getName(),1);
//            if (housePayWayBean.getDictId()!=null&&!TextUtils.isEmpty(housePayWayBean.getDictId()))
//            {
//                secondHandQueryParmar.setAreaId(Long.parseLong(housePayWayBean.getDictId()));
//            }
//            addressSelectOne=housePayWayBean;//默认选中的地址
//        }
        }
        //搜索结果跳转过来的
        includeTitleSearchBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSearchResult)
                {
                    isSearchResult=false;
                    secondhandShowIndicator.setVisibility(View.VISIBLE);
                    secondhandSerchResult.setVisibility(View.GONE);
                    secondhandTitle.setVisibility(View.VISIBLE);
                    secondhand_show_view.setVisibility(View.VISIBLE);
                    return;
                }
                killMyself();
            }
        });
        popuwindowSelectsearchaddressSearchRootlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopuwindowContralUtils.getPopuwindowContralUtils().showPopuWindowToSearch(SecondHandListShowActivity.this, includeTitleSearchXedit, new PopuWindowSearchHistoryInterface() {
                    @Override
                    public void callBack(String content, PopuWindowSelectSearchBean popuWindowSelectSearchBean) {
                        //搜索
                        secondhand_show_view.setVisibility(View.GONE);
                        secondHandQueryParmar = new SecondHandQueryParmar();
                        secondHandQueryParmar.setKeywords(popuWindowSelectSearchBean != null ? popuWindowSelectSearchBean.getContent() : content);
                        mPresenter.listSecondHand(secondHandQueryParmar);
                    }
                });
            }
        });

        //直接跳转过来的
        includeTitleSearchBackImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                killMyself();
            }
        });

        includeTitleSearchSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopuwindowContralUtils.getPopuwindowContralUtils().showPopuWindowToSearch(SecondHandListShowActivity.this, includeTitleSearchXedit, new PopuWindowSearchHistoryInterface() {
                    @Override
                    public void callBack(String content, PopuWindowSelectSearchBean popuWindowSelectSearchBean) {
                        secondhandSerchResult.setVisibility(View.VISIBLE);
                        secondhandTitle.setVisibility(View.GONE);
                        secondhandShowIndicator.setVisibility(View.GONE);
                        isSearchResult=true;
                        secondHandQueryParmar = new SecondHandQueryParmar();
                        secondHandQueryParmar.setKeywords(popuWindowSelectSearchBean != null ? popuWindowSelectSearchBean.getContent() : content);
                        mPresenter.listSecondHand(secondHandQueryParmar);
                    }
                });
            }
        });


        mPresenter.listSecondHand(secondHandQueryParmar);
        mPresenter.getAreaTree(Api.HOUSE_AREA, "", addressSelectData);
        mPresenter.dictList(Api.SECOND_HAND_LABEL, "", kjsxSelectData);

    }

    /**
     * 初始化弹出控件
     */
    public void initDropDownMenu() {
        dropDownMenu = (DropDownMenu) findViewById(R.id.dropDownMenu);
        pxView = LayoutInflater.from(this).inflate(R.layout.popuwindows_seelct_px, null);
        addressView = LayoutInflater.from(this).inflate(R.layout.popuwindows_seelct_second_adress, null);
        sxView = LayoutInflater.from(this).inflate(R.layout.secondhand_seelct_sx, null);
        popupViews.add(addressView);
        popupViews.add(pxView);
        popupViews.add(sxView);
        contentView = LayoutInflater.from(this).inflate(R.layout.secondhand_list_content, null);
        HouseRentingShowDuanZuList_RecyclerView = contentView.findViewById(R.id.HouseRentingShowDuanZuList_RecyclerView);
        HouseRentingShowMain_refreshLayout = contentView.findViewById(R.id.HouseRentingShowMain_refreshLayout);
        HouseRentingShowDuanZuList_RecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        HouseRentingShowDuanZuList_RecyclerView.addItemDecoration(new SpaceItemDecoration(AppUtil.dp2px(10)));
        secondHandMainShowAdapter = new SecondHandMainShowAdapter(new ArrayList<>());
        HouseRentingShowDuanZuList_RecyclerView.setAdapter(secondHandMainShowAdapter);
        secondHandMainShowAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        HouseRentingShowMain_refreshLayout.setEnableRefresh(false);//禁止下拉刷新
        dropDownMenu.setDropDownMenu(Arrays.asList(getResources().getStringArray(R.array.secondhand_show_list_select)), popupViews, contentView);
        dropDownMenu.setClickBtn(new DropDownMenu.ClickBtn() {
            @Override
            public void clikCallBack(View view) {
                if (addressSelectData == null) {
                    mPresenter.getAreaTree(Api.HOUSE_AREA, "", addressSelectData);//获取区域
                }
                if (kjsxSelectData != null && kjsxSelectData == null) {
                    mPresenter.dictList(Api.SECOND_HAND_LABEL, "", kjsxSelectData);
                }
            }
        });
        HouseRentingShowMain_refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                secondHandQueryParmar.setPage((secondHandQueryParmar.getPage() + 1));
                mPresenter.listSecondHand(secondHandQueryParmar);
            }
        });
        if (pxSecondHandSelectHolder == null) {
            pxSecondHandSelectHolder = new PxSecondHandSelectHolder(this, pxView, new PopuWindowSelectPxAdapter.BtncliickCallBack() {
                @Override
                public void callBack(int index, Object content) {

                    List<SecondHandQueryParmar.SortOrdersBean> sortOrdersBeans = new ArrayList<>();
                    sortOrdersBeans.add((SecondHandQueryParmar.SortOrdersBean) content);
                    secondHandMainShowAdapter.setNewData(null);
                    secondHandQueryParmar.setPage(1);
                    secondHandQueryParmar.setSortOrders(sortOrdersBeans);
                    mPresenter.listSecondHand(secondHandQueryParmar);
                    dropDownMenu.closeMenu();
                }
            });
        }
    }

    @Override
    public void showLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void listSecondHandSuccessa(int curryPage, int totalPage, List<SecondHandInfoBean> secondHandInfoBeans) {
        HouseRentingShowMain_refreshLayout.finishLoadMore();
        if (secondHandInfoBeans == null || secondHandInfoBeans.isEmpty()) {
            HouseRentingShowMain_refreshLayout.setEnableLoadMore(false);
            if (curryPage == 1) {
                secondHandMainShowAdapter.setEmptyView(AppUtil.setEmptyView(SecondHandListShowActivity.this, "没有搜索到相关信息，换个条件试试", "", null, true));
            }
            return;
        }
        secondHandQueryParmar.setPage(curryPage);
        if (curryPage >= totalPage) {
            HouseRentingShowMain_refreshLayout.setEnableLoadMore(false);
        } else {
            HouseRentingShowMain_refreshLayout.setEnableLoadMore(true);
        }
        if (secondHandMainShowAdapter.getData() == null || secondHandMainShowAdapter.getData().isEmpty()) {
            secondHandMainShowAdapter.setNewData(secondHandInfoBeans);
        } else {
            secondHandMainShowAdapter.addData(secondHandInfoBeans);
        }
    }

    @Override
    public void listSecondCategorySuccess(final List<SecondHandCategoryBean> secondHandCategoryBeans) {

    }

    public void flMenuContalShow(final List<SecondHandCategoryBean> secondHandCategoryBeans) {
        SecondHandCategoryBean secondHandCategoryBean = (SecondHandCategoryBean) getIntent().getSerializableExtra("SecondHandCategoryBean");
        secondHandCategoryBean.setName("全部");
        secondHandCategoryBeans.add(0, secondHandCategoryBean);
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return secondHandCategoryBeans.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {

                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context);
                simplePagerTitleView.setText(secondHandCategoryBeans.get(index).getName());
                DisplayMetrics dm = getResources().getDisplayMetrics();
                simplePagerTitleView.setTextSize(16);
                simplePagerTitleView.setNormalColor(getResources().getColor(R.color.color_191919));
                simplePagerTitleView.setSelectedColor(getResources().getColor(R.color.color_191919));
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

                simplePagerTitleView.setLayoutParams(layoutParams);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        secondhandShowIndicator.onPageSelected(index);
                        commonNavigator.getAdapter().notifyDataSetChanged();
                        //tab切换
                        secondHandMainShowAdapter.setNewData(null);
                        secondHandQueryParmar.setPage(1);
                        secondHandQueryParmar.setCategoryId(Long.parseLong(secondHandCategoryBeans.get(index).getCategoryId()));
                        mPresenter.listSecondHand(secondHandQueryParmar);
                    }
                });

                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                linePagerIndicator.setLineHeight(8.0f);
                linePagerIndicator.setColors(ArmsUtils.getColor(SecondHandListShowActivity.this, R.color.color_F9D35A));
                return linePagerIndicator;
            }

            @Override
            public float getTitleWeight(Context context, int index) {
                return 1.0f;
            }

        });
        secondhandShowIndicator.setNavigator(commonNavigator);
    }

    @Override
    public void dictListSuccess(String value, List<HousePayWayBean> housePayWayBeans) {
        switch (value) {
            case Api.HOUSE_AREA:
                this.addressSelectData = housePayWayBeans;
                if (addressSecondHandSelectHolder == null && housePayWayBeans != null && !housePayWayBeans.isEmpty()) {
                    //请求到地址后默认加载数据
                    addressSecondHandSelectHolder = new AddressSecondHandSelectHolder(this, addressView, housePayWayBeans, null, addressSelectOne);
                    addressSecondHandSelectHolder.init(new AddressSecondHandSelectHolder.SelectAddressCallBack() {
                        @Override
                        public void callBack(String type, int index, Object o) {
                            dropDownMenu.closeMenu();
                            secondHandMainShowAdapter.setNewData(null);
                            secondHandQueryParmar.setPage(1);
                            if (index == 0) {
                                dropDownMenu.setTabText("不限");
                                secondHandQueryParmar.setCategoryId(0l);
                                mPresenter.listSecondHand(secondHandQueryParmar);
                                return;
                            }
                            if (type.equals("区域")) {
                                addressSelectOne = (HousePayWayBean) o;
                                dropDownMenu.setTabText(type.equals("区域") ? ((HousePayWayBean) o).getName() : type);
                                secondHandQueryParmar.setCategoryId(Long.parseLong(addressSelectOne.getDictId()));
                                mPresenter.listSecondHand(secondHandQueryParmar);

                            } else {

                                //必须设置经纬度
                            }

                        }
                    });
                }
                break;
            case Api.SECOND_HAND_LABEL:
                //筛选
                kjsxSelectData = housePayWayBeans;
                sxSecondHandHolder = new SxSecondHandHolder(this, sxView);
                sxSecondHandHolder.init(housePayWayBeans, new SxSecondHandHolder.SxSelectCallback() {
                    @Override
                    public void callback(String beginSalePrice, String endSalePrice, List<String> labids) {
                        dropDownMenu.closeMenu();
                        secondHandMainShowAdapter.setNewData(null);
                        secondHandQueryParmar.setPage(1);
                        secondHandQueryParmar.setBeginSalePrice(beginSalePrice);
                        secondHandQueryParmar.setEndSalePrice(endSalePrice);
                        secondHandQueryParmar.setLabelIds(labids);
                        mPresenter.listSecondHand(secondHandQueryParmar);

                    }
                });
                break;
        }

    }


}
